//
//  DDNetWorkManager.m
//  DingDongZP
//
//  Created by Jyh on 16/3/17.
//  Copyright © 2016年 iyhjiang.com. All rights reserved.
//

#import "DDNetWorkManager.h"
#import "DDBaseModel.h"
#import "DDLoginUserManager.h"
#import "AFHTTPSessionManager.h"
#import "YYModel.h"
#import <objc/runtime.h>

@implementation DDNetWorkManager

+ (instancetype)shareManager
{
    static DDNetWorkManager *manager = nil;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[self alloc] init];
    });
    
    return manager;
}

- (instancetype)init
{
    self = [super init];
    
    if (self) {
        return self;
    }
    return self;
}

- (void)GET:(NSString *)URLString
 parameters:(id)parameters
    success:(void (^)(id responseObject))success
    failure:(void (^)(id responseObject, NSError *error))failure
{
    if (!URLString) {
        failure(@"URLString为空",nil);
    }
    
    if (!parameters) {
        parameters = [@{} mutableCopy];
    }
    
    //    NSLog(@"GET请求的URL---  %@",URLString);
    //    NSLog(@"GET请求的参数---  %@",parameters);
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"html/json",@"text/plain", nil];
    AFJSONResponseSerializer *jsonReponseSerializer = [AFJSONResponseSerializer serializer];
    // This will make the AFJSONResponseSerializer accept any content type
    jsonReponseSerializer.acceptableContentTypes = nil;
    manager.responseSerializer = jsonReponseSerializer;
    
    
    [UIApplication sharedApplication].networkActivityIndicatorVisible = true;
    [manager GET:URLString parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        
        [UIApplication sharedApplication].networkActivityIndicatorVisible = false;
        [self execCompletionBlockWithSuccess:success url:task.currentRequest.URL  responseObject:responseObject];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        [UIApplication sharedApplication].networkActivityIndicatorVisible = false;
        [self execCompletionBlockWithFailure:failure url:task.currentRequest.URL responseObject:task.response err:error];
    }];
}

- (void)POST:(NSString *)URLString
  parameters:(id)parameters
     success:(void (^)(id responseObject))success
     failure:(void (^)(id responseObject, NSError *error))failure
{
    if (!URLString) {
        failure(@"URLString为空",nil);
    }
    
    if (!parameters) {
        parameters = [@{} mutableCopy];
    }
    else {
        parameters = [parameters mutableCopy];
    }
    
    if (!parameters[@"hashedpassword"]) {
        [parameters setObject:[DDLoginUserManager token] forKey:@"hashedpassword"];
        NSLog(@"POST请求的hashedpassword---  %@",parameters[@"hashedpassword"]);
    }
    
    if (!parameters[@"mobile"]) {
        [parameters setObject:[DDLoginUserManager account] forKey:@"mobile"];
        NSLog(@"POST请求的mobile---  %@",parameters[@"mobile"]);
    }
    
    [UIApplication sharedApplication].networkActivityIndicatorVisible = true;
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"html/json",@"text/plain", nil];
    AFJSONResponseSerializer *jsonReponseSerializer = [AFJSONResponseSerializer serializer];
    // This will make the AFJSONResponseSerializer accept any content type
    jsonReponseSerializer.acceptableContentTypes = nil;
    manager.responseSerializer = jsonReponseSerializer;
    [manager POST:URLString parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        [UIApplication sharedApplication].networkActivityIndicatorVisible = false;
        [self execCompletionBlockWithSuccess:success url:task.currentRequest.URL  responseObject:responseObject];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        [UIApplication sharedApplication].networkActivityIndicatorVisible = false;
        [self execCompletionBlockWithFailure:failure url:task.currentRequest.URL responseObject:task.response err:error];
        
    }];
}

- (void)POSTWithNoToken:(NSString *)URLString
             parameters:(id)parameters
                success:(void (^)(id responseObject))success
                failure:(void (^)(id responseObject, NSError *error))failure
{
    if (!URLString) {
        failure(@"URLString为空",nil);
    }
    
    if (!parameters) {
        parameters = [@{} mutableCopy];
    }
    
    [UIApplication sharedApplication].networkActivityIndicatorVisible = true;
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"html/json",@"text/plain", nil];
    AFJSONResponseSerializer *jsonReponseSerializer = [AFJSONResponseSerializer serializer];
    
    jsonReponseSerializer.acceptableContentTypes = nil;
    manager.responseSerializer = jsonReponseSerializer;
    
    [manager POST:URLString parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        [UIApplication sharedApplication].networkActivityIndicatorVisible = false;
        [self execCompletionBlockWithSuccess:success url:task.currentRequest.URL  responseObject:responseObject];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        [UIApplication sharedApplication].networkActivityIndicatorVisible = false;
        [self execCompletionBlockWithFailure:failure url:task.currentRequest.URL responseObject:task.response err:error];
        
    }];
}

- (void)execCompletionBlockWithSuccess:(void (^)( id responseObject))success url:(NSURL *)url responseObject:(id)responseObject{
    
    [UIApplication sharedApplication].networkActivityIndicatorVisible = false;
    if (!success) { return; }
    
    bool isLogin = responseObject[@"code"];
    NSString *msg = responseObject[@"code"];
    if (isLogin == false && [msg containsString:@"账号或密码不符"] == true) {
        
        [[LDNetWorkManager sharedInstance] gotoLogin];
        
        return;
    }
    success(responseObject);
}

- (void)execCompletionBlockWithFailure:(void (^)( id responseObject,NSError * error))failure url:(NSURL *)url responseObject:(id)responseObject err:(NSError *)error{
    //    [[NSNotificationCenter defaultCenter] postNotificationName:@"kReachabilityChangedNotification" object:nil];
    if (!failure) {
        return;
    }
    failure(responseObject, error);
}

- (void)UPLOAD:(NSString *)URLString parameters:(id)parameters filesDatas:(NSDictionary *)files success:(void (^)(id))success failure:(void (^)(id, NSError *))failure
{
    if (!URLString) {
        failure(@"URLString为空",nil);
    }
    
    if (!parameters) {
        parameters = [@{} mutableCopy];
    }
    parameters = [parameters mutableCopy];
    if (!parameters[@"hashedpassword"]) {
        [parameters setObject:[DDLoginUserManager token] forKey:@"hashedpassword"];
    }
    
    if (!parameters[@"mobile"]) {
        [parameters setObject:[DDLoginUserManager account] forKey:@"mobile"];
    }
    //    NSLog(@"POST请求的URL---  %@",URLString);
    //    NSLog(@"POST请求的参数---  %@",parameters);
    
    [UIApplication sharedApplication].networkActivityIndicatorVisible = true;
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"html/json",@"text/plain", nil];
    AFJSONResponseSerializer *jsonReponseSerializer = [AFJSONResponseSerializer serializer];
    // This will make the AFJSONResponseSerializer accept any content type
    jsonReponseSerializer.acceptableContentTypes = nil;
    manager.responseSerializer = jsonReponseSerializer;
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    
    [manager POST:URLString parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData)
     {
         for (NSString *fname in files) {
             
             NSData *fdata = files[fname];
             if (fdata) {
                 
                 if ([fdata isKindOfClass:[UIImage class]]) {
                     fdata = UIImageJPEGRepresentation((UIImage *)fdata, 0.2);
                 }
                 [formData appendPartWithFileData:fdata
                                             name:fname
                                         fileName:fname
                                         mimeType:[self mimeWithData:fdata]];
             }
             
         }
         
     } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
         
         [UIApplication sharedApplication].networkActivityIndicatorVisible = false;
         [self execCompletionBlockWithSuccess:success url:task.currentRequest.URL  responseObject:responseObject];
     } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
         
         [UIApplication sharedApplication].networkActivityIndicatorVisible = false;
         [self execCompletionBlockWithFailure:failure url:task.currentRequest.URL responseObject:task.response err:error];
     }];
    
}

//上传语音
-(void)UPLOAD_VOICE:(NSString *)URLString parameters:(NSDictionary *)parameters filesDatas:(NSData *)filesDatas success:(void (^)(id))success failure:(void (^)(id, NSError *))failure {
    
    
    if (URLString == nil) {
        failure(@"URLString为空",nil);
    }
    
    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithDictionary:parameters];
    
    [dict setValue:[DDLoginUserManager token] forKey:@"hashedpassword"];
    [dict setValue:[DDLoginUserManager account] forKey:@"mobile"];
    
    
    [UIApplication sharedApplication].networkActivityIndicatorVisible = true;
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"html/json",@"text/plain", nil];
    AFJSONResponseSerializer *jsonReponseSerializer = [AFJSONResponseSerializer serializer];
    // This will make the AFJSONResponseSerializer accept any content type
    jsonReponseSerializer.acceptableContentTypes = nil;
    manager.responseSerializer = jsonReponseSerializer;
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    
    [manager POST:URLString parameters:dict constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData)
     {
         
         [formData appendPartWithFileData:filesDatas
                                     name:@"file"
                                 fileName:@"file"
                                 mimeType:@"audio/mpeg"];
         
     } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
         
         [UIApplication sharedApplication].networkActivityIndicatorVisible = false;
         [self execCompletionBlockWithSuccess:success url:task.currentRequest.URL  responseObject:responseObject];
     } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
         
         [UIApplication sharedApplication].networkActivityIndicatorVisible = false;
         [self execCompletionBlockWithFailure:failure url:task.currentRequest.URL responseObject:task.response err:error];
     }];
    
}

- (NSString *)mimeWithData:(NSData *)data
{
    uint8_t c;
    
    [data getBytes:&c length:1];
    
    NSString *mimeType=nil;
    
    switch (c) {
        case 0xFF:
            mimeType = @"image/jpeg";
            break;
        case 0x89:
            mimeType = @"image/png";
            break;
        case 0x47:
            mimeType = @"image/gif";
            break;
        case 0x49:
        case 0x4D:
            mimeType = @"image/tiff";
            break;
    }
    
    if(mimeType==nil){
        mimeType=@"image/jpeg";
        //        NSLog(@"Warnning:请注意，根据NSData获取图片的MimeType的时候出现错误：没有获取到值，框架默认‘image/jpeg’替换！");
    }
    
    return mimeType;
}

@end
